using UnityEngine;

namespace HotPlayer.Physic2D
{
    public class HotPhysic2DEngine
    {
        public static bool TestCollideGJK(Polygon2D polygon1, Polygon2D polygon2)
        {
            return GPTGJK.DetectCollision(polygon1, polygon2);
        }
        
        /// <summary>
        /// 碰撞检测
        /// </summary>
        /// <param name="polygon1"></param>
        /// <param name="polygon2"></param>
        /// <param name="direction">分离方向</param>
        /// <param name="point">碰撞点</param>
        /// <returns></returns>
        public static bool TestCollideGJK(Polygon2D polygon1, Polygon2D polygon2, out Vector2 direction, out Vector2 point)
        {
            var ret2 = GPTGJK.DetectCollision(polygon1, polygon2);
            if (ret2)
            {
                direction = EPA.ExpandPolytope(polygon1, polygon2, GJKUtils.simplex, out point);
            }
            else
            {
                point = Vector2.zero;
                direction = Vector2.zero;
            }
            
            return ret2;
        }

        public static bool TestCollideSAT(Polygon2D polygon1, Polygon2D polygon2)
        {
            return SAT.IsColliding(polygon1.pointsWS, polygon2.pointsWS);
        }
        
        public static bool TestCollideSAT(Polygon2D polygon1, Polygon2D polygon2, out Vector2 direction, out float mtv, out Vector2 contactPoint)
        {
            var c1 = polygon1.AveragePoint();
            var c2 = polygon2.AveragePoint();
            var c2Toc1 = c1 - c2;
            var isColliding = SAT.IsColliding(polygon1, polygon2, out direction, out mtv);
            if (Vector2.Dot(c2Toc1, direction) < 0)
            {
                direction = -direction;
            }
            contactPoint = isColliding ? SAT.GetContactPoint(polygon1, polygon2, direction, mtv) : Vector2.zero;
            return isColliding;
        }
    }
}